#!/bin/bash

me="${BASH_SOURCE[0]}"
SCRIPT_LOCATION=$(cd $(dirname `[ -L $me ] && readlink $me || echo $me`) && pwd -P)
MAIN_MK=build/core/main.mk

function get_android_root() {

    while true
    do
        if [ -f $MAIN_MK ]
        then
            echo "$(pwd)"
            break
        else
            cd ..    
            if [ $(pwd) == '/' ]
            then
                echo '/'
                return
            fi
        fi
    done 
}

function adbprepare() {
    set -x
    #adb kill-server; sleep 1
    #sudo adb start-server
    sudo adb wait-for-device

    adb root
    adb wait-for-device
    sleep 2
    adb remount
    adb wait-for-device
    sleep 1
    set -
        
    adb devices | grep -q 'no permissions'
    if [ 0 -eq $? ] ; then
        echo "no permissions"
        return 10
    else
        adb devices
    fi  

    return 0
}

function mypush() {
    sync
    local retry_count=1
    local current_count=1

    if [ $# != 2 ]
    then
        echo "usage: $0 src_name dst_name"
        return 8
    else
        device=$(adb devices | head -2 | tail -1 | awk '{print $1}')
        if [ -z "$device" ]
        then
            echo "error($0): no device found"
            return 9
        fi

        while true; do 
            echo "adb push $1 $2"
            adb push $1 $2 && return 0 
            echo -e "\nWill retry: adb push $1 $2"
            adbprepare
            [ $((current_count ++)) -gt $retry_count ] && return 10
        done

    fi

    return 11
}

#ARGS=`getopt -o ab:c:: --long a-long,b-long:,c-long:: -n 'example.bash' -- "$@"`
ARGS=`getopt -o p: --long remote,push,nopush -n "arg error" -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
eval set -- "$ARGS"
b_push=true
#build at remote(build server)
b_remote=false
while true; do
    case "$1" in
        "-p")
            b_push="$2"
            shift 2
            case "$b_push" in
                "0"|"false"|[Nn][Oo]|[Nn])
                    b_push=false
                    ;;
                "1"|"true"|[Yy][Ee][Ss]|[Yy])
                    b_push=true
                    ;;
            esac
            ;;
        "--push")
            b_push=true
            shift 1
            ;;
        "--nopush")
            b_push=false
            shift 1
            ;;
        "--remote")
            b_remote=true
            shift 1
            ;;
        --)
            shift 1
            break
            ;;
        *)
            echo "unknown arg: $1!"
            exit 1 
            ;;
    esac
done

root_dir=$(get_android_root)
if [ $root_dir == '/' ]; then
    echo "error: couldn't find android top dir, exit"
    exit
fi

DIR_BUILDLOG=/tmp/.$(whoami).buildlogs
mkdir -p $DIR_BUILDLOG
tmp_file=$(tempfile -d $DIR_BUILDLOG -p blog.)
tmp_file2=$(tempfile -d $DIR_BUILDLOG -p blog.)

trap "rm -f $tmp_file $tmp_file2" EXIT

#if build on remote, run ssh && cd to the correct directory, and build, then push at local site
if $b_remote; then
    project_name="$(basename $root_dir)"
    current_dir="$(pwd | awk -F"$(basename $root_dir)" '{print $2}')"
    remote_exec="cd ~/projects/${project_name}${current_dir}; bash -l -c '~/mybin/$(basename $0) --nopush $@'"

    ssh $(lutong) -t "$remote_exec" | tee $tmp_file

    cat $tmp_file | grep "src_name->dst_name:" | awk -F"[: ]" '{print $3 " " $4}' > $tmp_file2
    
    if cd $root_dir; then
        CMD_PUSH=$(cat $tmp_file2 | sed 's/^/mypush /g' | sed 's/\r$/ || exit 22;/g')
        sleep 1
        eval $CMD_PUSH
    fi

    exit
fi

module="" #build module by 'Make'
if echo "$(basename $0)" | grep -q "mymkpush" ; then
    module="$1"; shift
    if [ -z "$module" ]; then echo "!! Need module_name !!"; exit 13; fi
fi

export | grep JAVA_HOME

cd $root_dir

#target_product=$(echo "$1" | awk -F- '{print $1}')
#build_variant=$(echo "$1" | awk -F- '{print $2}')
#if [ -z "$TARGET_PRODUCT" -o -n "$target_product" -a "$TARGET_PRODUCT" != "$target_product"\
#    -o -z "$TARGET_BUILD_VARIANT" -o -n "$build_variant" -a "$TARGET_BUILD_VARIANT" != "$build_variant" ]; then

    source build/envsetup.sh
    echo "lunch $1"
    lunch $1 || exit 15
    shift
#fi

nJobs=$(grep processor /proc/cpuinfo | awk '{field=$NF};END{print field+1}')
nJobs=8
echo "<<<<< build start >>>>>"

build_exit_code=0
if echo "$(basename $0)" | grep -q "mymmpush" ; then
    cd -
    echo "mm -j$nJobs | tee $tmp_file"
    mm -j$nJobs | tee $tmp_file
    build_exit_code=$?
    cd -
elif echo "$(basename $0)" | grep -q "mymmapush" ; then
    cd -
    echo "mma -j$nJobs | tee $tmp_file"
    mma -j$nJobs | tee $tmp_file
    build_exit_code=$?
    cd -
elif echo "$(basename $0)" | grep -q "mymkpush" ; then
    [ -n "$module" ] && echo "make -j$nJobs $module" && make -j$nJobs $module | tee $tmp_file
    build_exit_code=$?
fi

if [ $build_exit_code != 0 ]; then 
    echo "build error, exit"
    exit $build_exit_code
fi
echo "<<<<< build done >>>>>"

installs_raw=$(grep '^Install: out/target/' $tmp_file | awk '{print $2}')
for aInstall in "$installs_raw"; do 
    [ -n "$aInstall" ] && md5sum $aInstall
    installs[${#installs[@]}]="$aInstall"
done

#product_name=$(grep '^Install: out/target' $tmp_file | awk -F'/' '{print $4}')
product_name=$(grep "TARGET_PRODUCT=" $tmp_file | tail -1 | awk -F= '{print $2}')
echo "product_name = $product_name"

echo "root_dir = $root_dir"
echo "installs = ${installs[@]}"
[ -z "${installs[*]}" ] && echo "No Change, Nothing has been built"
for src_name in ${installs[@]} ; do
    dst_name="/${src_name#*/$product_name/}"
	echo "src_name->dst_name: $src_name $dst_name"
    
    if $b_push; then
        mypush $root_dir/$src_name $dst_name || break
    fi
done

exit $?
